<!--长效养护-->
<template>
  <page-meta
    :page-font-size="baseFontSize + 'rpx'"
    :root-font-size="baseFontSize + 'rpx'"
  ></page-meta>
  <view class="app-container">
    <!-- 审批信息 -->
    <uni-card
      class="box-card"
      v-loading="processInstanceLoading"
      v-for="(item, index) in runningTasks"
      :key="index"
    >
      <view slot="header" class="clearfix">
        <text class="el-icon-picture-outline">审批任务【{{ item.name }}】</text>
      </view>
      <view>
        <uni-forms
          :ref="'form' + index"
          :modelValue="auditForms[index]"
          :rules="auditRule"
          label-width="110px"
        >
          <uni-forms-item label="流程名" v-if="processInstance && processInstance.name">
            {{ processInstance.name }}
          </uni-forms-item>
          <uni-forms-item
            label="流程发起人"
            v-if="processInstance && processInstance.startUser"
          >
            {{ processInstance.startUser.nickname }}
            <el-tag type="info" size="mini">{{
              processInstance.startUser.deptName
            }}</el-tag>
          </uni-forms-item>
          <uni-forms-item label="审批建议" prop="reason">
            <el-input
              type="textarea"
              v-model="auditForms[index].reason"
              placeholder="请输入审批建议"
            />
          </uni-forms-item>
          <uni-forms-item
            label="期望完成时间"
            prop="expectEndDate"
            v-if="
              processInstance.name?.indexOf('案卷') > -1 &&
              tasks[0]?.name?.indexOf('监理') > -1
            "
          >
            <el-date-picker
              clearable
              v-model="auditForms[index].expectEndDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择期望完成时间"
            />
          </uni-forms-item>
          <!-- 当到了施工负责人节点的时候 需要施工负责人做案卷任务分配  start-->
          <view v-if="tasks[0]?.name?.indexOf('施工单位') > -1">
            <el-row>
              <view>
                <uni-forms-item label="任务名称">
                  {{ taskObj.taskName }}
                </uni-forms-item>
              </view>
              <view>
                <uni-forms-item label="养护项目" prop="projectManageId">
                  {{ taskObj.projectName }}
                </uni-forms-item>
              </view>
              <view>
                <uni-forms-item label="关联设施" prop="facilityId">
                  <view>{{ form.facilityName }}</view>
                </uni-forms-item>
              </view>
              <!-- <view >
                <uni-forms-item label="养护等级" >
                  <el-select class="w100" v-model="form.maintenanceLevel" placeholder="请选择养护等级">
                    <el-option v-for="dict in this.getDictDatas(DICT_TYPE.XCJK_MAINTENANCE_LEVEL)"
                      :key="parseInt(dict.value)" :label="dict.label" :value="parseInt(dict.value)" />
                  </el-select>
                </uni-forms-item>
              </view> -->
              <view>
                <uni-forms-item label="案卷来源" prop="caseIds">
                  <view>{{ form.caseCode }}</view>
                </uni-forms-item>
              </view>
            </el-row>
            <el-row>
              <view>
                <uni-forms-item label="期望完成时间">
                  {{ expectEndDate }}
                  <!-- <el-date-picker clearable v-model="auditForms[index].expectEndDate" type="date"
                    value-format="yyyy-MM-dd" placeholder="选择期望完成时间" /> -->
                </uni-forms-item>
              </view>
            </el-row>
            <uni-forms-item label="维修方案">
              <uni-easyinput
                type="textarea"
                :inputBorder="false"
                v-model="taskObj.content"
                placeholder="请输入维修方案"
              />
            </uni-forms-item>
            <uni-forms-item label="任务分配" prop="taskUserId">
              <!-- <taskSetModal
                @change="taskChange"
                :taskUserId="auditForms[index].taskUserId"
                :taskUserNickname="auditForms[index].taskUserNickname"
              /> -->
            </uni-forms-item>
          </view>
          <!-- 当到了施工负责人节点的时候 需要施工负责人做案卷任务分配  end-->
        </uni-forms>
        <view style="margin-left: 10%; margin-bottom: 20px; font-size: 14px">
          <button
            icon="el-icon-edit-outline"
            type="success"
            size="mini"
            @click="handleAudit(item, true)"
          >
            通过
          </button>
          <button
            icon="el-icon-circle-close"
            type="danger"
            size="mini"
            @click="handleAudit(item, false)"
          >
            不通过
          </button>
          <button
            icon="el-icon-edit-outline"
            type="primary"
            size="mini"
            @click="handleUpdateAssignee(item)"
          >
            转办
          </button>
        </view>
      </view>
    </uni-card>
    <!-- 申请信息 -->
    <uni-card class="box-card" v-loading="processInstanceLoading">
      <view slot="header" class="clearfix">
        <text class="el-icon-document">申请信息【{{ processInstance.name }}】</text>
      </view>
      <view
        v-if="
          this.processInstance.processDefinition &&
          this.processInstance.processDefinition.formType === 20
        "
      >
        <view class="case-detail" v-if="processInstance.name?.indexOf('案卷') > -1">
          <!-- <caseDetail :form="form"></caseDetail> -->
        </view>

        <view class="case-detail" v-else-if="processInstance.name?.indexOf('任务') > -1">
          施工详情
          <view v-for="item in taskDetail.handleCases">
            <!-- <constructionDetail :cDetail="item"></constructionDetail> -->
          </view>
          任务详情
          <!-- <taskDetail :taskDetail="taskDetail"></taskDetail> -->
          <!-- 案卷详情
          <caseDetail :form='taskDetail.case'></caseDetail> -->
        </view>
      </view>
    </uni-card>

    <!-- 审批记录 -->
    <uni-card class="box-card" v-loading="tasksLoad">
      <view slot="header" class="clearfix">
        <text class="el-icon-picture-outline">审批记录</text>
      </view>
      <view>
        <!-- <taskTimeline :tasks="tasks"></taskTimeline> -->
      </view>
    </uni-card>

    <!-- 高亮流程图 -->
    <uni-card class="box-card" v-loading="processInstanceLoading">
      <view slot="header" class="clearfix">
        <text class="el-icon-picture-outline">流程图</text>
      </view>
      <!-- <my-process-viewer
        key="designer"
        v-model="bpmnXML"
        v-bind="bpmnControlForm"
        :activityData="activityList"
        :processInstanceData="processInstance"
        :taskData="tasks"
      /> -->
    </uni-card>

    <!-- 对话框(转派审批人) -->
    <!-- <el-dialog
      title="转派审批人"
      :visible.sync="updateAssignee.open"
      width="500px"
      append-to-body
    >
      <uni-forms
        ref="updateAssigneeForm"
        :modelValue="updateAssignee.form"
        :rules="updateAssignee.rules"
        label-width="110px"
      >
        <uni-forms-item label="新审批人" prop="assigneeUserId">
          <el-select
            v-model="updateAssignee.form.assigneeUserId"
            clearable
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="item in userOptions"
              :key="parseInt(item.id)"
              :label="item.nickname"
              :value="parseInt(item.id)"
            />
          </el-select>
        </uni-forms-item>
      </uni-forms>
      <view slot="footer" class="dialog-footer">
        <button type="primary" @click="submitUpdateAssigneeForm">确 定</button>
        <button @click="cancelUpdateAssigneeForm">取 消</button>
      </view>
    </el-dialog> -->
  </view>
</template>

<script>
import {
  createDmTask,
  getDmTaskPage,
  getCaseManage,
  getProcessDefinitionBpmnXML,
  getDmProjectManagePage,
  getProcessInstance,
  approveTask,
  setExpect,
  getTaskListByProcessInstanceId,
  rejectTask,
  updateTaskAssignee,
  queryExpect,
  listSimpleUsers,
  getActivityList
} from '@/api/common.js';
// import { DICT_TYPE, getDictDatas } from '@/utils/dict';
import store from '@/store';
import { decodeFields } from '@/utils/util';
import { getDate } from '@/utils/util';
// 流程实例的详情页，可用于审批
export default {
  name: 'ProcessInstanceDetail',
  components: {
    // taskSetModal,
    // caseDetail,
    // taskDetail
    // constructionDetail,
    // taskTimeline
  },
  data() {
    return {
      isPass: true,
      expectEndDate: null,
      taskObj: {
        maintenanceLevel: '1',
        projectName: '',
        taskName: '',
        expectEndDate: null,
        content: null,
        taskUserId: null,
        taskUserNickname: null,
        projectManageId: null
      },
      form: {
        brokenImg: []
      },
      taskDetail: {},
      // 遮罩层
      processInstanceLoading: true,
      // 流程实例
      id: undefined, // 流程实例的编号
      processInstance: {},

      // 流程表单详情
      detailForm: {
        fields: []
      },

      // BPMN 数据
      bpmnXML: null,
      bpmnControlForm: {
        prefix: 'flowable'
      },
      activityList: [],

      // 审批记录
      tasksLoad: true,
      tasks: [],

      // 审批表单
      runningTasks: [],
      auditForms: [],
      auditRule: {
        reason: [{ required: true, message: '审批建议不能为空', trigger: 'blur' }],
        expectEndDate: [
          {
            validator: this.validExpectEndDate,
            trigger: ['blur', 'change']
          }
        ],
        taskUserId: [
          {
            validator: this.validtaskUserId,
            trigger: ['blur', 'change']
          }
        ]
      },

      // 转派审批人
      userOptions: [],
      updateAssignee: {
        open: false,
        form: {
          assigneeUserId: undefined
        },
        rules: {
          assigneeUserId: [
            { required: true, message: '新审批人不能为空', trigger: 'change' }
          ]
        }
      }
    };
  },
  created() {
    this.id = this.$route.query.id;
    if (!this.id) {
      this.$message.error('未传递 id 参数，无法查看流程信息');
      return;
    }
    this.getDetail();

    // 获得用户列表
    this.userOptions = [];
    listSimpleUsers().then((response) => {
      this.userOptions.push(...response.data);
    });
  },
  methods: {
    validtaskUserId(rule, value, callback) {
      // const index = this.runningTasks?.indexOf(task)
      if (!this.auditForms[0].taskUserId && this.isPass) {
        callback('任务分配人员不能为空');
      } else {
        callback();
      }
    },
    validExpectEndDate(rule, value, callback) {
      // const index = this.runningTasks?.indexOf(task)
      if (!this.auditForms[0].expectEndDate && this.isPass) {
        callback('期望完成时间不能为空');
      } else {
        callback();
      }
    },
    taskChange(data) {
      console.log(
        '%c [ data ]-317',
        'font-size:13px; background:pink; color:#bf2c9f;',
        data
      );
      this.auditForms[0].taskUserId = data.id;
      this.auditForms[0].taskUserNickname = data.username;
    },
    //获取项目名称
    async getProjectManage(facilityId) {
      const res = await getDmProjectManagePage({
        pageNo: 1,
        pageSize: 10,
        facilityId
      });
      this.taskObj.projectManageId = res.data?.list[0]?.projectManageId;
      this.taskObj.projectName = res.data?.list[0]?.projectName;
    },
    queryExpect() {
      const caseId = this.processInstance.businessKey;

      queryExpect(caseId).then((res) => {
        this.expectEndDate = res.data;
      });
    },
    /** 获取案卷详情 */
    getCaseDetail() {
      const id = this.processInstance.businessKey;
      getCaseManage(id).then((response) => {
        console.log(
          '%c [ response ]-205',
          'font-size:13px; background:pink; color:#bf2c9f;',
          response
        );
        let {
          lng,
          lat,
          deviceType,
          brokenImg,
          caseCode,
          facilityName,
          belongTo: facilityId
        } = response.data;
        this.form = {
          ...response.data,
          lnglat: `${lng},${lat}`,
          deviceType: parseInt(deviceType),
          brokenImg: brokenImg
            ? brokenImg?.split(',').map((item) => {
                return {
                  url: item
                };
              })
            : []
        };
        this.taskObj.taskName = `${facilityName}-${caseCode}`;
        this.getProjectManage(facilityId);
      });
    },
    /** 获取任务详情 */
    getTaskDetail() {
      const id = this.processInstance.businessKey;
      console.log('%c [ id ]-440', 'font-size:13px; background:pink; color:#bf2c9f;', id);
      let params = {
        pageNo: 1,
        pageSize: 10,
        taskType: 1,
        taskId: id
      };
      getDmTaskPage(params).then((response) => {
        console.log(
          '%c [ response ]-205',
          'font-size:13px; background:pink; color:#bf2c9f;',
          response
        );
        let resData = response.data.list[0];
        let {
          lng,
          lat,
          deviceType,
          brokenImg,
          caseCode,
          facilityName,
          belongTo: facilityId
        } = resData.cases[0];
        let handleCases = resData.cases.map((item) => {
          let {
            lng,
            lat,
            deviceType,
            brokenImg,
            caseCode,
            facilityName,
            belongTo: facilityId
          } = item;
          return {
            ...item,
            lnglat: `${lng},${lat}`,
            deviceType: parseInt(deviceType),
            brokenImg: brokenImg
              ? brokenImg?.split(',').map((item) => {
                  return {
                    url: item
                  };
                })
              : []
          };
        });
        this.taskDetail = {
          ...resData,
          handleCases,
          case: {
            ...resData.cases[0],
            lnglat: `${lng},${lat}`,
            deviceType: parseInt(deviceType),
            brokenImg: brokenImg
              ? brokenImg?.split(',').map((item) => {
                  return {
                    url: item
                  };
                })
              : []
          }
        };
      });
    },
    /** 获得流程实例 */
    getDetail() {
      // 获得流程实例相关
      this.processInstanceLoading = true;
      getProcessInstance(this.id).then((response) => {
        if (!response.data) {
          this.$message.error('查询不到流程信息！');
          return;
        }
        // 设置流程信息
        this.processInstance = response.data;

        // 设置表单信息
        if (this.processInstance.processDefinition.formType === 10) {
          this.detailForm = {
            ...JSON.parse(this.processInstance.processDefinition.formConf),
            disabled: true, // 表单禁用
            formBtns: false, // 按钮隐藏
            fields: decodeFields(this.processInstance.processDefinition.formFields)
          };
          // 设置表单的值
          this.detailForm.fields.forEach((item) => {
            const val = this.processInstance.formVariables[item.__vModel__];
            if (val) {
              item.__config__.defaultValue = val;
            }
          });
        }

        // 加载流程图
        getProcessDefinitionBpmnXML(this.processInstance.processDefinition.id).then(
          (response) => {
            this.bpmnXML = response.data;
          }
        );

        //加载案卷详情
        if (this.processInstance.name?.indexOf('案卷') > -1) {
          // if (this.tasks[0]?.name?.indexOf('施工单位') > -1) {//|| this.tasks[0]?.name?.indexOf('业主') > -1
          //   this.queryExpect()
          // }
          this.getCaseDetail();
          this.queryExpect();
        }

        //加载任务详情
        if (this.processInstance.name?.indexOf('任务') > -1) {
          this.getTaskDetail();
        }

        // 加载活动列表
        getActivityList({
          processInstanceId: this.processInstance.id
        }).then((response) => {
          this.activityList = response.data;
        });

        // 取消加载中
        this.processInstanceLoading = false;
      });

      // 获得流程任务列表（审批记录）
      this.tasksLoad = true;
      this.runningTasks = [];
      this.auditForms = [];
      getTaskListByProcessInstanceId(this.id).then((response) => {
        // 审批记录
        this.tasks = [];
        // 移除已取消的审批
        response.data.forEach((task) => {
          if (task.result !== 4) {
            this.tasks.push(task);
          }
        });
        // 排序，将未完成的排在前面，已完成的排在后面；
        this.tasks.sort((a, b) => {
          // 有已完成的情况，按照完成时间倒序
          if (a.endTime && b.endTime) {
            return b.endTime - a.endTime;
          } else if (a.endTime) {
            return 1;
          } else if (b.endTime) {
            return -1;
            // 都是未完成，按照创建时间倒序
          } else {
            return b.createTime - a.createTime;
          }
        });

        // 需要审核的记录
        const userId = store.getters.userId;
        this.tasks.forEach((task) => {
          if (task.result !== 1) {
            // 只有待处理才需要
            return;
          }
          if (!task.assigneeUser || task.assigneeUser.id !== userId) {
            // 自己不是处理人
            return;
          }
          this.runningTasks.push({ ...task });
          this.auditForms.push({
            reason: ''
          });
        });

        // 取消加载中
        this.tasksLoad = false;
      });
    },
    /** 处理审批通过和不通过的操作 */
    handleAudit(task, pass) {
      this.isPass = pass;
      const index = this.runningTasks?.indexOf(task);
      if (pass && this.auditForms[index].reason === '') {
        this.auditForms[index].reason = '通过';
      }
      if (!pass && this.auditForms[index].reason === '') {
        this.auditForms[index].reason = '驳回';
      }
      this.$refs['form' + index][0].validate(async (valid) => {
        if (!valid) {
          return;
        }
        const data = {
          id: task.id,
          reason: this.auditForms[index].reason
        };
        if (pass) {
          if (this.tasks[0]?.name?.indexOf('施工单位') > -1) {
            let res = await createDmTask(this.createTask());
            if (Number(res.code) != 0) {
              this.$modal.msgError(res.msg);
              return false;
            }
          }
          approveTask(data).then((response) => {
            if (
              this.processInstance.name?.indexOf('案卷') > -1 &&
              this.tasks[0]?.name?.indexOf('监理') > -1
            ) {
              setExpect({
                expectDate: this.auditForms[index].expectEndDate,
                caseId: this.processInstance.businessKey
              }).then((res) => {
                this.$modal.msgSuccess('审批通过成功！');
              });
            } else {
              this.$modal.msgSuccess('审批通过成功！');
            }
            this.getDetail(); // 获得最新详情
          });
        } else {
          let processType = '',
            processInstanceId = task.id;
          if (this.processInstance.name?.indexOf('案卷') > -1) {
            processType = 'case_manage';
          }
          if (this.processInstance.name?.indexOf('任务') > -1) {
            processType = 'task_manage';
          }

          rejectTask({ ...data, processType }).then((response) => {
            this.$modal.msgSuccess('审批不通过成功！');
            this.getDetail(); // 获得最新详情
          });
        }
      });
    },
    /** 创建任务 */
    createTask() {
      this.form.projectManageId = parseInt(this.form.projectManageId);
      this.form.facilityId = parseInt(this.form.belongTo);
      let { id, belongTo: facilityId } = this.form;
      let { taskUserNickname, taskUserId } = this.auditForms[0];
      let { expectEndDate } = this;
      let { taskName, projectManageId, maintenanceLevel, content } = this.taskObj;
      let params = {
        facilityId,
        taskType: 1,
        caseIds: [id],
        taskName,
        projectManageId,
        taskUserNickname,
        taskUserId,
        expectEndDate,
        maintenanceLevel,
        content
      };
      // 添加的提交
      return { ...params };

      // if (Number(res.code) != 0) {
      //   this.$modal.msgError(res.msg)
      //   return false
      // } else {
      //   return true
      // }
    },
    /** 处理转派审批人 */
    handleUpdateAssignee(task) {
      // 设置表单
      this.resetUpdateAssigneeForm();
      this.updateAssignee.form.id = task.id;
      // 设置为打开
      this.updateAssignee.open = true;
    },
    /** 提交转派审批人 */
    submitUpdateAssigneeForm() {
      this.$refs['updateAssigneeForm'].validate((valid) => {
        if (!valid) {
          return;
        }
        updateTaskAssignee(this.updateAssignee.form).then((response) => {
          this.$modal.msgSuccess('转派任务成功！');
          this.updateAssignee.open = false;
          this.getDetail(); // 获得最新详情
        });
      });
    },
    /** 取消转派审批人 */
    cancelUpdateAssigneeForm() {
      this.updateAssignee.open = false;
      this.resetUpdateAssigneeForm();
    },
    /** 重置转派审批人 */
    resetUpdateAssigneeForm() {
      this.updateAssignee.form = {
        id: undefined,
        assigneeUserId: undefined
      };
      this.resetForm('updateAssigneeForm');
    },
    /** 处理审批退回的操作 */
    handleDelegate(task) {
      this.$modal.msgError('暂不支持【委派】功能，可以使用【转派】替代！');
    },
    /** 处理审批退回的操作 */
    handleBack(task) {
      this.$modal.msgError('暂不支持【退回】功能！');
      // 可参考 http://blog.wya1.com/article/636697030/details/7296
      // const data = {
      //   id: task.id,
      //   assigneeUserId: 1
      // }
      // backTask(data).then(response => {
      //   this.$modal.msgSuccess("回退成功！");
      //   this.getDetail(); // 获得最新详情
      // });
    }
  }
};
</script>

<style lang="scss" scoped>
@import '../richangxuncha/index.scss';

.list-area {
  height: 300upx;
}

.u-page {
  background: #fff;
  height: 100vh;
}

.top-wrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background: #fff;
  padding: 0 22upx;
}

.btn {
  color: #fff;
  width: 160upx;
  height: 4.8rem;
  background: #597ef7;
  border-radius: 8upx;
  color: #fff;
  line-height: 4.8rem;
  text-align: center;
}

/deep/.uni-searchbar {
  background: #f1f1f1;
}
.fontList {
  position: fixed;
  display: flex;
  justify-content: space-around;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 30upx 20upx;
  background: #fff;
}
.time view:nth-of-type(2) {
  display: flex;
  margin: 10upx 0;
  img {
    width: 200upx;

    margin-right: 5upx;
  }
}
/deep/ .uni-searchbar__box-search-input {
  height: 40upx !important;
}
.img-box {
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  grid-gap: 40rpx;
  gap: 40rpx;
  img {
    width: 66px;
  }
}
.my-process-designer {
  height: calc(100vh - 200px);
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.app-container .el-input.is-disabled .el-input__inner {
  background-color: transparent;
  border-color: transparent;
  color: #000;
  cursor: default;
}
</style>
